package co.fitstart.admin.web.controller.course;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.BusinessException;
import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.DateFormatUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.web.utils.WebUtils;

import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.service.OfflineRoundService;
import co.fitstart.admin.service.PrincipalService;
import co.fitstart.admin.service.SiteService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.course.Course;
import co.fitstart.entity.course.CourseType;
import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.principal.Principal;
import co.fitstart.entity.site.Site;

/**
 * 
 * @author lidan
 *
 */
@Controller
@RequestMapping("/group-rounds")
@MenuSetting("menu-course")
public class GroupRoundController {
    
    private static final Logger logger = LoggerFactory.getLogger(GroupRoundController.class);
    
    @Autowired
    private OfflineRoundService offlineRoundService;
    
    @Autowired
    private SiteService siteService;
    
    @Autowired
    @Qualifier("dataService")
    private DataService<Course> courseService;
    
    @Autowired
    private PrincipalService principalService;
    
    /**
     * 
     * @param login
     * @param siteId
     * @param status
     * @param page
     * @param request
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    @MenuSetting("submenu-group-course-arrange")
    public ModelAndView list(@Secure Login login,
                             @RequestParam(value = "site", required = false) Long siteId,
                             @RequestParam(name = "status", required = false, defaultValue = "arranging") String status,
                             Page page,
                             HttpServletRequest request){

        ModelAndView modelAndView = new ModelAndView("course/group/group-round-list");
        
        Site site = null;
        if(!login.hasSite() && siteId != null) {
            site = siteService.load(siteId);
        }else if (login.hasSite()){
            site = login.getSite();
        }
        
        List<CourseRound> courseRounds = new ArrayList<>();
        
        if(site == null && (login.isAreaManager() || login.isAreaServer())) {
            Principal principal = principalService.load(Principal.class, login.getId());
            
            List<Site> sites = siteService.listSite(principal);
            
            if(!sites.isEmpty()) {
                courseRounds = offlineRoundService.listGroupRound(sites, status, CourseType.GROUP, page);
            }
        } else {
            courseRounds = offlineRoundService.listGroupRound(site, status, CourseType.GROUP, page);
        }
        
        modelAndView.addObject("courseRounds", courseRounds);
        
        modelAndView.addObject("status", status);

        modelAndView.addObject("page", page);
        
        modelAndView.addObject("refer", "list");
        modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page","status"));
        return modelAndView;
    }
    
    /**
     * Display group round create panel
     * 
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create() {
        
        ModelAndView modelAndView = new ModelAndView("course/group/group-round-create");
        
        return modelAndView;
    }
    
    /**
     * List round json data for selection
     * 
     * @param courseId 
     * @return
     */
    @RequestMapping(value = "/list-selection", method = RequestMethod.GET)
    public @ResponseBody String listSelection(@Secure Login login,
                                              @RequestParam(value = "course") Long courseId) {
        
        Result result = new Result();
        
        try {
            Course course = courseService.load(Course.class, courseId);
            
            List<Site> sites = null;
            
            if(login.hasSite()) {
                sites = new ArrayList<>();
                
                sites.add(login.getSite());
            } else if(login.isAreaManager() || login.isAreaServer()) {
                Principal principal = principalService.load(Principal.class, login.getId());
                
                sites = siteService.listSite(principal);
            }
            
            List<Map<String, Object>> courseRounds = new ArrayList<>();
            
            if(sites == null) {
                courseRounds = offlineRoundService.listCourseRound(CourseType.GROUP, course);
            } else if(!sites.isEmpty()) {
                courseRounds = offlineRoundService.listCourseRound(CourseType.GROUP, course, sites);
            }
            
            result.success().message("加载学员成功")
                            .data("courseRounds", courseRounds);
            
        } catch (Exception e) {
            
            result.fail().message("加载学员失败");
            
            logger.error("#listStudent() error ", e);
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * On create group round (generate round code)
     * 
     * @param roundIds
     * @param courseId 
     * @param courseCode 
     * @param gym 
     * @param startDate 
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody String onCreate(@RequestParam(value = "roundIds") List<Long> roundIds,
                                         @RequestParam(value = "courseId") Long courseId,
                                         @RequestParam(value = "courseCode") String courseCode,
                                         @RequestParam(value = "gym") String gym,
                                         @RequestParam(value = "startDate") String startDate) {
        
        Result result = new Result();
        
        try {
            
            Course course = courseService.load(Course.class, courseId);
            
            if(course.getNumbers() < roundIds.size()) {
                
                result.fail().message("学员数量超过团课人数");
                
                return JsonUtils.toJsonString(result);
                
            }
            
            List<CourseRound> courseRounds = offlineRoundService.listCourseRound(roundIds);
            
            offlineRoundService.generateGroup(courseRounds, courseCode, gym, startDate);;
            
            result.success().message("创建团课成功");
            
        } catch (Exception e) {
            
            result.fail().message("创建团课失败");
            
            logger.error("#listStudent() error ", e);
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * View round time arrange page
     * 
     * @param roundCode
     * @return
     */
    @RequestMapping(value = "/{roundCode}/arrange", method = RequestMethod.GET)
    public ModelAndView arrange(@PathVariable("roundCode") String roundCode) {
        
        ModelAndView modelAndView = new ModelAndView("course/group/group-round-arrange");
        
        // only load one round by code
        CourseRound courseRound = offlineRoundService.loadCourseRound(roundCode);
        
        modelAndView.addObject("courseRound", courseRound);
        
        modelAndView.addObject("today", DateFormatUtils.format(new Date(), "yyyy-MM-dd"));
        
        return modelAndView;
    }
    
    /**
     * Do arrange time
     * 
     * @param roundCode
     * @param beginDate 
     * @param dayhour
     * @return
     */
    @RequestMapping(value = "/{roundCode}/arrange", method = RequestMethod.PATCH)
    public @ResponseBody String onArrange(@PathVariable("roundCode") String roundCode,
                                          @RequestParam("beginDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date beginDate,
                                          @RequestParam(value = "dayhour") String ... dayhour) {
        
        Result result = new Result();
        
        try {
            
            List<CourseRound> courseRounds = offlineRoundService.listCourseRound(roundCode);
            
            offlineRoundService.arrangeGroup(courseRounds, beginDate, dayhour);
            
            result.success().message("排期成功");
            
        } catch (BusinessException e) {
            
            result.fail().message(e.getMessage());
            
        } catch (Exception e) {
            
            result.fail().message("排期失败");
            
            logger.error("#onArrange() error ", e);
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * View round detail
     * 
     * @param roundCode
     * @return
     */
    @RequestMapping(value = "/{roundCode}", method = RequestMethod.GET)
    @MenuSetting("submenu-group-course-arrange")
    public ModelAndView view(@PathVariable("roundCode") String roundCode) {
        
        ModelAndView modelAndView = new ModelAndView("course/group/group-round-view");
        
        List<CourseRound> courseRounds = offlineRoundService.listCourseRound(roundCode);
        
        modelAndView.addObject("courseRounds", courseRounds);
        
        return modelAndView;
    }
    

}
